#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021-11-24 15:33
# @Author : huabao.tan
# @File : get_wangzherongyao_picture.py
# @Software: PyCharm

import os
import parsel
import requests
import re
import tkinter as tk
from tkinter import filedialog

def save_file():
    root = tk.Tk()
    root.withdraw()
    Fpath = filedialog.asksaveasfilename()
    return Fpath


def get_response(html_url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
    response = requests.get(url=html_url, headers=headers)
    # 万能转码方式
    response.encoding = response.apparent_encoding
    return response


def get_image_url(hero_id):
    hero_url = f'https://pvp.qq.com/web201605/herodetail/{hero_id}.shtml'
    response = get_response(hero_url)
    selector = parsel.Selector(response.text)
    hero_name = selector.css('.cover-name::text').get()
    skin_name = re.findall('<ul class="pic-pf-list pic-pf-list3" data-imgname="(.*?)">', response.text)[0].split('|')
    num = len(skin_name)
    a = 0
    for page in range(1, int(num) + 1):
        a = a + 1
        image_url = f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{hero_id}/{hero_id}-bigskin-{page}.jpg'
        image_content = get_response(image_url).content
        path = r'C:\Users\huabao.tan.CORP\Desktop\图片\\'
        path1 = path + f'{hero_name}\\'
        if not os.path.exists(path1):
            os.makedirs(path1)
        filename = path1 + skin_name[int(page) - 1].split('&')[0] + '.jpg'
        with open(filename, mode='wb') as f:
            f.write(image_content)
            print(a, ":", f'正在保存：{hero_name}', skin_name[int(page) - 1].split('&')[0])

def begin():
    url = 'https://pvp.qq.com/web201605/js/herolist.json'
    json_data = get_response(url).json()
    for i in json_data:
        hero_id = i['ename']
        get_image_url(hero_id)

if __name__ == '__main__':
   begin()
